
package com.scs.application.modules.base.controller;


import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.scs.application.core.excel.handler.ExcelDictHandlerImpl;
import com.scs.application.core.exceptions.BusinessException;
import com.scs.application.core.exceptions.ExportException;
import com.scs.application.core.exceptions.ImportException;
import com.scs.application.core.model.CommonResult;
import com.scs.application.core.model.ImportResult;
import com.scs.application.core.model.PageResult;
import com.scs.application.core.model.RestResult;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.mvc.controller.ImAndExAbleController;
import com.scs.application.core.utils.BeanUtils;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.core.utils.PoiUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.base.dto.ExcelSupplierDTO;
import com.scs.application.modules.base.dto.LoginKeyDTO;
import com.scs.application.modules.base.entity.HospitalSupplier;
import com.scs.application.modules.base.entity.Supplier;
import com.scs.application.modules.base.request.HospitalSupplierQueryRequest;
import com.scs.application.modules.base.request.SupplierQueryRequest;
import com.scs.application.modules.base.service.SupplierService;
import com.scs.application.modules.design.service.QueryGenerator;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 供应商 controller
 */
@AllArgsConstructor
@RestController
@SuppressWarnings("all")
@RequestMapping("/base/suppliers")
public class SupplierController extends CrudController<Supplier, String, SupplierService> implements ImAndExAbleController<SupplierQueryRequest> {

    @GetMapping("/page")
    public PageResult page(SupplierQueryRequest request) {
        IPage page = service.page(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }

    @PostMapping("/add")
    public CommonResult addSupplier(@RequestBody @Valid Supplier entity) {
        service.addSupplier(entity);
        return CommonResult.ok("新增成功", entity);
    }

    @Override
    @PutMapping
    public CommonResult update(@RequestBody @Valid Supplier entity) {
        Supplier supplier = this.service.getOne(Wrappers.<Supplier>query().ne("id", entity.getId()).eq("name", entity.getName()));
        if (supplier != null) {
            throw new BusinessException("供应商已经存在");
        }
        boolean bUpdate = service.updateCascadeById(entity);
        return bUpdate ? CommonResult.ok("保存成功", entity) : CommonResult.error("保存失败");
    }

    /***
     * @param entity
     * @Description:  通用保存、更新
     */
    @PostMapping("/saveOrUpdateCommon")
    public RestResult saveOrUpdateCommon(@Valid @RequestBody Supplier entity) {
        if (entity.isNewRecord()) {
            service.addSupplier(entity);
        }else{
            this.update(entity);
        }
        return RestResult.ok("数据保存成功", entity);
    }

    /**
     * 修改账号
     *
     * @param id
     * @param newLoginKey
     * @return
     */
    @PostMapping("/change_login_key")
    public CommonResult changeLoginKey(@RequestBody @Valid LoginKeyDTO dto) {
        service.changeLoginKey(dto.getId(), dto.getNewLoginKey());
        return CommonResult.ok("修改成功");
    }


    @GetMapping("/list")
    public CommonResult list(SupplierQueryRequest request) {
        List<Supplier> list = service.list(request);
        return CommonResult.ok("查询成功", list);
    }


    /**
     * 获取当前登录供应商信息
     */
    @GetMapping("/get_current_supplier")
    public CommonResult getCurrentSupplier() {
        String supplierId = UserUtils.getSupplierId();
        Supplier supplier = service.getById(supplierId);
        // com.scs.application.modules.base.vo.SupplierVO supplier = UserUtils.getUser().getSupplier();
        return CommonResult.ok("查询成功", supplier);
    }

    /**
     * 查询当前医院下不存在的供应商信息
     *
     * @param request
     * @return
     */
    @GetMapping("/page_hospital_not_existed")
    public PageResult pageHospitalNotExisted(SupplierQueryRequest request) {
        IPage<Supplier> page = service.pageHospitalNotExisted(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }


    /**
     * 供应商导出数据
     */
    @Override
    public void excelExport(SupplierQueryRequest request) {
        String fileName = "供应商信息" + DateUtils.format(DateUtils.now(), "yyyyMMddHHmmss") + ".xlsx";

        ExportParams params = new ExportParams("供应商信息", "供应商信息", ExcelType.XSSF);
        params.setDictHandler(ExcelDictHandlerImpl.getInstance());
        List<Supplier> list = service.list(request);
        List<ExcelSupplierDTO> dtos = Lists.newArrayListWithCapacity(list.size());
        BeanUtils.copyProperties(list, dtos, ExcelSupplierDTO.class);

        try {
            setDownloadParam(fileName);
            PoiUtils.exportExcel(response().getOutputStream(), "供应商信息", ExcelSupplierDTO.class, dtos, true);
        } catch (IOException e) {
            throw new ExportException("导出异常", e);
        }
    }

    /**
     * 供应商导出数据模板
     */
    @Override
    public void excelTemplate(SupplierQueryRequest request) {
        String fileName = "2供应商导入.xlsx";

        ExportParams params = PoiUtils.getDefaultExportParams("供应商导入模板", "供应商信息", true);
        // params.setExclusions(new String[]{"错误行号", "错误消息", "助记码", "登录账号"});
        params.setExclusions(new String[]{"错误行号", "错误消息", "助记码"});

        ExcelSupplierDTO mockData = PoiUtils.mockData(ExcelSupplierDTO.class);
        try {
            setDownloadParam(fileName);
            PoiUtils.exportExcel(response().getOutputStream(), params, ExcelSupplierDTO.class, Lists.newArrayList(mockData));
        } catch (IOException e) {
            throw new ExportException("导出异常", e);
        }
    }

    /**
     * 供应商导入数据
     */
    @Override
    public CommonResult<ImportResult> excelImport(MultipartFile file) throws ImportException {
        return CommonResult.ok("导入成功", service.excelImport(file));
    }


    /***
     * @param request
     * @date: 2024/6/21
     * @Description:  分页选择
     */
    @GetMapping("/pageSelect")
    public PageResult pageSelect(HttpServletRequest request,@RequestParam Map<String, String> reqData) {
        IPage<Supplier> page = QueryGenerator.parsePage(request);
        QueryWrapper<Supplier> queryWrapper = QueryGenerator.initQueryWrapper(request);
        String hospitalId=null;
        if (reqData.containsKey("userParam")) {
            JSONObject ob = JSON.parseObject(reqData.get("userParam") + "");
            hospitalId = ob.getString("hospitalId");
            HospitalSupplierQueryRequest hospitalSupplierQueryRequest = new HospitalSupplierQueryRequest();
            hospitalSupplierQueryRequest.setHospitalId(hospitalId);
            List<HospitalSupplier> hospitalSupplierList = hospitalSupplierService.list(Wrappers.<HospitalSupplier>query().eq("hospital_id",hospitalId));
            if (!hospitalSupplierList.isEmpty()) {
                List<String> supIdList = hospitalSupplierList.stream().map(HospitalSupplier::getSupplierId).distinct().collect(Collectors.toList());
                queryWrapper.in("id", supIdList);
            } else {
                queryWrapper.eq("id", "-1");
            }
        }
        IPage pageResult = service.page(page, queryWrapper);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }

}
